//
//  LXTYQBirthdayVC.swift
//  LuoXuanTYQ
//
//  Created by 李东 on 2024/3/17.
//

import UIKit
import SnapKit
import UniformTypeIdentifiers

class LXTYQBirthdayVC: LXTYQBaseVC {
    
    var scrollView: UIScrollView!
    var titleTF: UITextField!
    var dateLabel: UILabel!
    var desTF: UITextField!
    var collectView: UICollectionView!
    var createBtn: UIButton!
    var deleteBtn: UIButton!
    var saveBtn: UIButton!
    
    var model = LXTYQBirthdayModel()
    let CellID = "PicCellID"
    let itemW: CGFloat = (CGFloat.screenWidth-60)/3
    lazy var imgList = [UIImage]()
    
    init(model: LXTYQBirthdayModel = LXTYQBirthdayModel()) {
        super.init(nibName: nil, bundle: nil)
        self.model = model
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        hideNavgaitionBar()
        showBgImgView = true
        showPopBtn = true
        initUI()
        if model.ids == 0 {
            navTitle = "创建新的日历事件"
            createBtn.isHidden = false
            saveBtn.isHidden = true
            deleteBtn.isHidden = true
        }else {
            navTitle = model.title
            createBtn.isHidden = true
            saveBtn.isHidden = false
            deleteBtn.isHidden = false
            titleTF.text = model.title
            desTF.text = model.des
            dateLabel.text = dateformatter.string(from: Date(timeIntervalSince1970: TimeInterval(model.ts)))
            dateLabel.textColor = .white
        }
    }
    
    lazy var dateformatter: DateFormatter = {
        let tf = DateFormatter()
        tf.dateFormat = "yyyy年MM月dd"
        return tf
    }()
    
    func initUI()  {
        scrollView = UIScrollView()
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(CGFloat.navHeight)
            make.width.equalTo(CGFloat.screenWidth)
        }
        
        let view1 = initView1()
        scrollView.addSubview(view1)
        view1.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.width.equalTo(CGFloat.screenWidth-40)
            make.top.equalTo(30)
        }
        
        let view2 = initView2()
        scrollView.addSubview(view2)
        view2.snp.makeConstraints { make in
            make.left.right.equalTo(view1)
            make.top.equalTo(view1.snp.bottom).offset(30)
        }

        let view3 = initView3()
        scrollView.addSubview(view3)
        view3.snp.makeConstraints { make in
            make.left.right.equalTo(view1)
            make.top.equalTo(view2.snp.bottom).offset(30)
        }
        
        let picView = initPicView()
        scrollView.addSubview(picView)
        picView.snp.makeConstraints { make in
            make.left.right.equalTo(view1)
            make.top.equalTo(view3.snp.bottom).offset(30)
        }
        
        createBtn = UIButton()
        createBtn.setImage(UIImage(named: "img_create"), for: .normal)
        createBtn.addTarget(self, action: #selector(createHandle), for: .touchUpInside)
        scrollView.addSubview(createBtn)
        createBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(picView.snp.bottom).offset(30)
        }
        
        saveBtn = UIButton()
        saveBtn.setImage(UIImage(named: "img_save_edit"), for: .normal)
        saveBtn.addTarget(self, action: #selector(saveEditHandle), for: .touchUpInside)
        scrollView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.centerY.equalTo(createBtn)
            make.left.equalTo(scrollView.snp.centerX).offset(5)
        }
        
        deleteBtn = UIButton()
        deleteBtn.setImage(UIImage(named: "img_delete_event"), for: .normal)
        deleteBtn.addTarget(self, action: #selector(deleteEventHandle), for: .touchUpInside)
        scrollView.addSubview(deleteBtn)
        deleteBtn.snp.makeConstraints { make in
            make.centerY.equalTo(createBtn)
            make.right.equalTo(scrollView.snp.centerX).offset(-5)
        }
    }
    

    func initView1() -> UIView {
        let tempView = UIView()
        let topLabel1 = UILabel()
        topLabel1.textColor = .init(hex: 0xB4B4B4)
        topLabel1.font = UIFont.systemFont(ofSize: 14)
        topLabel1.text = "标题"
        tempView.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
        }
        
        titleTF = UITextField()
        titleTF.textColor = .white
        titleTF.attributedPlaceholder = NSAttributedString(string: "请输入标题限制10个字符", attributes: [.foregroundColor: UIColor.init(hex: 0x666666)])
        titleTF.font = UIFont.systemFont(ofSize: 14)
        titleTF.delegate = self
        tempView.addSubview(titleTF)
        titleTF.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topLabel1.snp.bottom).offset(5)
            make.height.equalTo(40)
        }
        
        let line = UIView()
        line.backgroundColor = .init(hex: 0x362D47)
        tempView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(titleTF.snp.bottom)
        }
        return tempView
    }
    
    
    func initView2() -> UIView {
        let tempView = UIView()
        let topLabel1 = UILabel()
        topLabel1.textColor = .init(hex: 0xB4B4B4)
        topLabel1.font = UIFont.systemFont(ofSize: 14)
        topLabel1.text = "日期"
        tempView.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
        }
        
        dateLabel = UILabel()
        dateLabel.textColor = .init(hex: 0x666666)
        dateLabel.text = "点击选择日期"
        dateLabel.font = UIFont.systemFont(ofSize: 14)
        dateLabel.isUserInteractionEnabled = true
        dateLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectDate)))
        tempView.addSubview(dateLabel)
        dateLabel.snp.makeConstraints { make in
            make.top.equalTo(topLabel1.snp.bottom).offset(5)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        }
        
        let line = UIView()
        line.backgroundColor = .init(hex: 0x362D47)
        tempView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(dateLabel.snp.bottom)
        }
        return tempView
    }

    func initView3() -> UIView {
        let tempView = UIView()
        let topLabel1 = UILabel()
        topLabel1.textColor = .init(hex: 0xB4B4B4)
        topLabel1.font = UIFont.systemFont(ofSize: 14)
        topLabel1.text = "描述"
        tempView.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
        }
        
        desTF = UITextField()
        desTF.textColor = .white
        desTF.attributedPlaceholder = NSAttributedString(string: "请输入内容", attributes: [.foregroundColor: UIColor.init(hex: 0x666666)])
        desTF.font = UIFont.systemFont(ofSize: 14)
        tempView.addSubview(desTF)
        desTF.snp.makeConstraints { make in
            make.top.equalTo(topLabel1.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        }
        
        let line = UIView()
        line.backgroundColor = .init(hex: 0x362D47)
        tempView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(desTF.snp.bottom)
        }
        return tempView
    }
    
    func initPicView() -> UIView {
        let tempView = UIView()
        let topLabel1 = UILabel()
        topLabel1.textColor = .init(hex: 0xB4B4B4)
        topLabel1.font = UIFont.systemFont(ofSize: 14)
        topLabel1.text = "上传图片"
        tempView.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.scrollDirection = .vertical
        
        collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.backgroundColor = .clear
        collectView.showsVerticalScrollIndicator = false
        collectView.delegate = self
        collectView.dataSource = self
        collectView.register(UINib(nibName: "LXTYQPicCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CellID)
        tempView.addSubview(collectView)
        collectView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(topLabel1.snp.bottom).offset(15)
            make.height.equalTo(getCollectionViewHeight())
        }
        return tempView
    }
    
    @objc func createHandle()  {
        if titleTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入标题")
            return
        }
        if dateLabel.text == "点击选择日期" {
            showHUDTextOnly("请选择日期")
            return
        }
        if model.ids == 0 {
            model.ids = Int(Date().timeIntervalSince1970)
        }
        model.title = titleTF.text ?? ""
        model.ts = Int(dateformatter.date(from: dateLabel.text!)!.timeIntervalSince1970)
        model.des = desTF.text ?? ""
        LXTYQBirthdayHelper.shared.addDate(model: model)
        showHUDTextOnly("当前事件已保存") {[weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func saveEditHandle() {
        if titleTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入标题")
            return
        }
        if dateLabel.text == "点击选择日期" {
            showHUDTextOnly("请选择日期")
            return
        }
        if model.ids == 0 {
            model.ids = Int(Date().timeIntervalSince1970)
        }
        model.title = titleTF.text ?? ""
        model.ts = Int(dateformatter.date(from: dateLabel.text!)!.timeIntervalSince1970)
        model.des = desTF.text ?? ""
        LXTYQBirthdayHelper.shared.addDate(model: model)
        showHUDTextOnly("当前事件已保存") {[weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func deleteEventHandle() {
        let vc = UIAlertController(title: "确定删除当前事件吗？", message: "删除后不可恢复", preferredStyle: .alert)
        let act1 = UIAlertAction(title: "取消", style: .cancel)
        let act2 = UIAlertAction(title: "确认", style: .default) {[weak self] _ in
            guard let self = self else {
                return
            }
            LXTYQBirthdayHelper.shared.deleteDate(ids: self.model.ids)
            self.navigationController?.popViewController(animated: true)
        }
        vc.addAction(act1)
        vc.addAction(act2)
        present(vc, animated: true)
    }
    
    @objc func selectDate() {
        let vc = LXTYQDatePickerVC()
        vc.modalPresentationStyle = .overFullScreen
        vc.finish = {[weak self] dd in
            guard let self = self else {
                return
            }
            self.dateLabel.text = dateformatter.string(from: dd)
            self.model.ts = Int(TimeInterval(dd.timeIntervalSince1970))
            self.dateLabel.textColor = .white
        }
        present(vc, animated: true)
    }
    
    func showPicPicker()  {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action1 = UIAlertAction(title: "相机", style: .default) { _ in
            self.selectPhoto(type: .camera)
        }
        let action2 = UIAlertAction(title: "相册", style: .default) { _ in
            self.selectPhoto(type: .photoLibrary)
        }
        let action3 = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)
        present(alert, animated: true)
        
    }
    
    func selectPhoto(type: UIImagePickerController.SourceType)  {
        RXPermissionUtils.albumAndCamera(type: type) {[weak self] in
            guard let self = self else {
                return
            }
            let picker = UIImagePickerController()
            picker.sourceType = type
            picker.delegate = self
            picker.allowsEditing = false
            if #available(iOS 14.0, *) {
                picker.mediaTypes = [UTType.image.identifier]
            } else {
                // Fallback on earlier versions
                picker.mediaTypes = ["images"]
            }
            self.present(picker, animated: true)
        }
   
    }
    
    func getCollectionViewHeight() -> CGFloat {
        var c_h : CGFloat = 0
        if model.picList.count == 9 {
            c_h = itemW * 3 + 20
        }else{
            let a = (model.picList.count + 1)/3
            let b = (model.picList.count + 1)%3
            if b > 0 {
                c_h = CGFloat(a+1) * itemW + CGFloat(a * 10)
            }else{
                c_h = CGFloat(a)*itemW + CGFloat((a-1)*10)
            }
        }
        return c_h
    }
}

extension LXTYQBirthdayVC: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let strLength = (textField.text?.count)! - range.length + string.count
        return strLength <= 10
    }
}

extension LXTYQBirthdayVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        guard let img = info[.originalImage] as? UIImage else {
            return
        }
        let fileName = "\(Date().timeIntervalSince1970).png"
        CompressedHelper.shared.writeData(data: img.pngData()!, fileName: fileName)
        model.picList.append(fileName)
        collectView.reloadData()
        collectView.snp.updateConstraints { make in
            make.height.equalTo(getCollectionViewHeight())
        }
        
    }
    
    
}

extension LXTYQBirthdayVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        model.picList.count >= 9 ? model.picList.count : model.picList.count+1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath) as! LXTYQPicCollectionViewCell
        if model.picList.count < 9 && model.picList.count == indexPath.row {
            cell.deleteBtn.isHidden = true
            cell.picImgView.contentMode = .center
            cell.picImgView.image = UIImage(named: "icon_upload")
        }else {
            cell.deleteBtn.isHidden = false
            cell.picImgView.contentMode = .scaleAspectFill
            cell.picImgView.image = UIImage(contentsOfFile: CompressedHelper.shared.getFilePath(fileName: model.picList[indexPath.row]))
        }
        cell.deleteCallBack = {[weak self] in
            guard let self = self else {
                return
            }
            CompressedHelper.shared.deleteFile(fileName: self.model.picList[indexPath.row])
            self.model.picList.remove(at: indexPath.row)
            self.collectView.reloadData()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if model.picList.count < 9 && model.picList.count == indexPath.row {
            showPicPicker()
        }
    }
    
}
